<template>
  <div :class="counterClass">
    <slot name="left"></slot><span ref="number" :id="eleId"></span><slot name="right"></slot>
  </div>
</template>

<script>
import CountUp from 'countup'

export default {
  name: 'WCount',
  props: {
    /**
     * @description 延时加载毫秒
     */
    delay: {
      type: Number,
      default: 0
    },
    /**
     * @description 起始值
     */
    startVal: {
      type: Number,
      default: 0
    },
    /**
     * @description 最终值(必填)
     */
    endVal: {
      type: Number,
      required: true
    },
    /**
     * @description 小数点后保留几位
     */
    decimals: {
      type: Number,
      default: 0
    },
    /**
     * @description 动画持续时间(秒)
     */
    duration: {
      type: Number,
      default: 2
    },
    /**
     * @description 动画是否变速
     */
    useEasing: {
      type: Boolean,
      default: true
    },
    /**
     * @description  是否使用分组效果
     */
    useGrouping: {
      type: Boolean,
      default: true
    },
    /**
     * @description  分隔符样式定义
     */
    separator: {
      type: String,
      default: ','
    },
    /**
     * @description 整数和小数的隔离样式
     */
    decimal: {
      type: String,
      default: '.'
    }
  },
  data (){
    return {
      counter: {}
    }
  },
  computed: {
    eleId () {
      return `counter_${this._uid}`
    },
    counterClass () {
      return [
        'counter'
      ]
    }
  },
  methods: {
    getCount () {
      return this.$refs.number.innerText
    },
    emitEndEvent () {
      setTimeout(() => {
        this.$emit('on-anmiation-end', Number(this.getCount()))
      }, this.decimals * 1000);
    }
  },
  watch: {
    endVal (newVal, oldVal) {
      this.counter.update(newVal)
      this.emitEndEvent()
    }
  },
  // 在所有组件挂在完成后调用,但是不能保证所有组件都渲染完成,确保所有组件渲染完成需要用到$nextTick函数
  mounted () {
    this.$nextTick(() => {
       this.counter = new CountUp(this.eleId, this.startVal, this.endVal, this.decimals, this.duration, {
        useEasing: this.useEasing,
        useGrouping: this.useGrouping,
        separator: this.separator,
        decimal: this.decimal
      })
    })
    setTimeout(() => {
      this.counter.start()
      this.emitEndEvent()
    }, this.delay);
  }
}
</script>

<style>

</style>
